package Core;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;


/**
 * Prompts for text and sends it via an SMS MessageConnection
 */
public class SMSSender implements Runnable {

	private String destinationAddress;
	private String data;
	private Event sendSuccessAction, sendFailAction;

	public SMSSender(String data, String destinationAddress, Event good, Event fail) {
		this.data = data;
		this.destinationAddress = destinationAddress;
		sendSuccessAction = good;
		sendFailAction = fail;
	}

	public void Start() {
		Thread thread = new Thread(this);
		thread.start();
	}

	public void run() {
		String address = "sms://" + this.destinationAddress;
		MessageConnection smsconn = null;
		try {
			/** Open the message connection. */
			smsconn = (MessageConnection) Connector.open(address);
			TextMessage txtmessage = (TextMessage) smsconn.newMessage(MessageConnection.TEXT_MESSAGE);
			txtmessage.setAddress(address);
			txtmessage.setPayloadText(data);
			smsconn.send(txtmessage);
			if(sendSuccessAction!=null)
				sendSuccessAction.action();
	
		} catch (Throwable t) {
			t.printStackTrace();
			if(sendFailAction!=null)
				sendFailAction.action();
		}finally{
			try {
				if(smsconn!=null)
					smsconn.close();
				;//System.out.println("dong ket noi trong send sms");
			} catch (IOException ioe) {
				;//System.out.println("Closing connection caught: ");
				ioe.printStackTrace();
			}
		}
	}

	public static void sendSMSToConfirmReward(String sms, String destinationAddress, 
			final Event actionAfterConfirm, final Event actionFailAfterConfirm) {
		SMSSender sender = new SMSSender(sms, destinationAddress, actionAfterConfirm, actionFailAfterConfirm);
        sender.Start();
	}
}
